import logging

from flask import Blueprint, abort, jsonify, request
from flask_restful import reqparse

from src import db
from src.models.dictionary_model import Dictionary

base_meta_data_bp = Blueprint("base_meta", __name__, url_prefix="/api/meta")


@base_meta_data_bp.route("/add", methods=["POST"])
def add_base_meta():
    """添加一条字典数据"""
    parser = reqparse.RequestParser()
    parser.add_argument("dict_type", type=str, required=True, location="json")
    parser.add_argument("dict_label", type=str, required=True, location="json")
    parser.add_argument("dict_value", type=str, required=True, location="json")
    parser.add_argument("extras", type=dict, required=False, location="json")
    args = parser.parse_args()

    try:
        DictionaryCls = Dictionary(**args)
        db.session.add(DictionaryCls)
        db.session.commit()
        logger = logging.getLogger(__name__)
        logger.info("插入成功，主键ID: %s", DictionaryCls.id)
        return (
            jsonify({"success": True, "message": "ok", "data": DictionaryCls.id}),
            200,
        )
    except Exception as e:
        logger = logging.getLogger(__name__)
        logger.error("添加字典数据失败: %s", e, exc_info=True)
        return jsonify({"success": False, "message": str(e)}), 500


@base_meta_data_bp.route("/list", methods=["POST"])
def get_dict_list():
    form_data: dict[str, any] = request.get_json()
    page = form_data.get("page", 1)
    per_page = form_data.get("per_page", 10)
    dict_type = form_data.get("dict_type")
    status = form_data.get("status")
    if dict_type is None:
        return jsonify({"success": False, "errMsg": "请选择字典类型"}), 500
    query = Dictionary.query.filter(Dictionary.dict_type == dict_type)
    if status is not None:
        query = query.filter(Dictionary.status == status)
    pagination = query.order_by(Dictionary.id.desc()).paginate(page=page, per_page=per_page, error_out=False)
    dict_items: list[Dictionary] = pagination.items
    logging.info("dict_items: %s", dict_items)
    return jsonify(
        {
            "success": True,
            "message": "ok",
            "data": [dict_item.to_dict() for dict_item in dict_items],
            # "data": [dict_item.model_dump(['dict_value','dict_label']) for dict_item in dict_items],
            "total": pagination.total,
            "page": page,
            "per_page": per_page,
        }
    )


@base_meta_data_bp.route("/remove", methods=["POST"])
def remove_one_meta():
    form_data: dict[str, any] = request.get_json()
    primary_id = form_data.get("id")
    if primary_id is None:
        return jsonify({"success": False, "errMsg": "无效操作"}), 500
    dictionary = Dictionary.query.get(primary_id)
    if dictionary is None:
        return jsonify({"success": False, "errMsg": "记录不存在"}), 500
    try:
        dictionary.status = 0
        db.session.commit()
        return jsonify({"success": True, "message": "ok", "data": True})
    except Exception as e:
        logger = logging.getLogger(__name__)
        logger.error("更新字典数据失败: %s", e, exc_info=True)
        return jsonify({"success": False, "message": str(e)}), 500


@base_meta_data_bp.route("/update", methods=["POST"])
def update_one_meta():
    json_data = request.get_json(silent=True) or abort(400)
    pk = json_data.get("id")
    if pk is None:
        return jsonify({"success": False, "errMsg": "无效操作"}), 500

    ALLOWED_COLS = {c.name for c in Dictionary.__table__.columns} - {
        "id",
        "status",
        "gmt_create",
        "gmt_modified",
        "gmt",
    }  # 主键不可改
    # 1. 取出要改的记录
    target_record = Dictionary.query.get_or_404(pk)

    # 3. 白名单过滤
    to_update = {k: v for k, v in json_data.items() if k in ALLOWED_COLS}
    if not to_update:  # 请求里什么都没有可改的
        return jsonify({"success": False, "errMsg": "无需更新"}), 500

    # 一次性赋值 + 自动校验
    for key, value in to_update.items():
        setattr(target_record, key, value)

    try:
        # 提交
        db.session.commit()
        return jsonify({"success": True, "message": "ok", "data": True})
    except Exception as e:
        print("update dict error", e)
        return jsonify({"success": False, "message": str(e)}), 500
